using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using CKY.AgentPlatform.Domain.Performance;
using CKY.AgentPlatform.Authorization;

namespace CKY.AgentPlatform.Application.Performance
{
    /// <summary>
    /// 数据库性能优化应用服务
    /// 提供数据库性能监控和优化建议
    /// </summary>
    [Authorize]
    public class DatabasePerformanceAppService : ApplicationService
    {
        private readonly DatabasePerformanceService _databasePerformanceService;

        public DatabasePerformanceAppService(DatabasePerformanceService databasePerformanceService)
        {
            _databasePerformanceService = databasePerformanceService;
        }

        /// <summary>
        /// 获取数据库性能统计信息
        /// </summary>
        public async Task<DatabasePerformanceStatsDto> GetPerformanceStatsAsync()
        {
            var stats = await _databasePerformanceService.GetPerformanceStatsAsync();

            return new DatabasePerformanceStatsDto
            {
                Timestamp = stats.Timestamp,
                ConnectionCount = stats.ConnectionCount,
                ActiveTransactions = stats.ActiveTransactions,
                CacheHitRate = Math.Round(stats.CacheHitRate, 2),
                AverageQueryTime = Math.Round(stats.AverageQueryTime, 2),
                SlowQueryCount = stats.SlowQueryCount,
                IndexUsageStats = stats.IndexUsageStats.Select(i => new IndexUsageStatDto
                {
                    TableName = i.TableName,
                    IndexName = i.IndexName,
                    UsageCount = i.UsageCount,
                    TotalSeeks = i.TotalSeeks,
                    TotalScans = i.TotalScans,
                    TotalLookups = i.TotalLookups,
                    TotalUpdates = i.TotalUpdates
                }).ToList(),
                TableSizeStats = stats.TableSizeStats.Select(t => new TableSizeStatDto
                {
                    TableName = t.TableName,
                    RowCount = t.RowCount,
                    TotalSpaceKB = t.TotalSpaceKB,
                    DataSpaceKB = t.DataSpaceKB,
                    IndexSpaceKB = t.IndexSpaceKB
                }).ToList()
            };
        }

        /// <summary>
        /// 获取数据库优化建议
        /// </summary>
        public async Task<List<DatabaseOptimizationRecommendationDto>> GetOptimizationRecommendationsAsync()
        {
            var recommendations = await _databasePerformanceService.GetOptimizationRecommendationsAsync();

            return recommendations.Select(r => new DatabaseOptimizationRecommendationDto
            {
                Type = r.Type,
                Severity = r.Severity,
                Title = r.Title,
                Description = r.Description,
                Recommendation = r.Recommendation
            }).ToList();
        }

        /// <summary>
        /// 清理数据库缓存
        /// </summary>
        [Authorize(AgentPlatformPermissions.Performance.Manage)]
        public async Task ClearDatabaseCacheAsync()
        {
            await _databasePerformanceService.ClearDatabaseCacheAsync();
        }

        /// <summary>
        /// 获取数据库健康状态
        /// </summary>
        public async Task<DatabaseHealthStatusDto> GetHealthStatusAsync()
        {
            var stats = await _databasePerformanceService.GetPerformanceStatsAsync();

            // 计算健康评分
            var healthScore = CalculateHealthScore(stats);

            // 判断健康状态
            var status = healthScore >= 80 ? "Healthy" : healthScore >= 60 ? "Warning" : "Critical";

            return new DatabaseHealthStatusDto
            {
                Status = status,
                HealthScore = healthScore,
                Timestamp = DateTime.UtcNow,
                Checks = new List<HealthCheckItem>
                {
                    new HealthCheckItem
                    {
                        Name = "连接数",
                        Value = stats.ConnectionCount,
                        Status = stats.ConnectionCount < 100 ? "Healthy" : stats.ConnectionCount < 200 ? "Warning" : "Critical",
                        Threshold = "Max: 100 connections"
                    },
                    new HealthCheckItem
                    {
                        Name = "活跃事务",
                        Value = stats.ActiveTransactions,
                        Status = stats.ActiveTransactions < 20 ? "Healthy" : stats.ActiveTransactions < 50 ? "Warning" : "Critical",
                        Threshold = "Max: 20 transactions"
                    },
                    new HealthCheckItem
                    {
                        Name = "缓存命中率",
                        Value = stats.CacheHitRate,
                        Status = stats.CacheHitRate >= 80 ? "Healthy" : stats.CacheHitRate >= 60 ? "Warning" : "Critical",
                        Threshold = "Min: 80%"
                    },
                    new HealthCheckItem
                    {
                        Name = "平均查询时间",
                        Value = stats.AverageQueryTime,
                        Status = stats.AverageQueryTime < 200 ? "Healthy" : stats.AverageQueryTime < 500 ? "Warning" : "Critical",
                        Threshold = "Max: 200ms"
                    },
                    new HealthCheckItem
                    {
                        Name = "慢查询数量",
                        Value = stats.SlowQueryCount,
                        Status = stats.SlowQueryCount < 5 ? "Healthy" : stats.SlowQueryCount < 10 ? "Warning" : "Critical",
                        Threshold = "Max: 5 queries"
                    }
                }
            };
        }

        /// <summary>
        /// 计算数据库健康评分
        /// </summary>
        private int CalculateHealthScore(DatabasePerformanceStats stats)
        {
            var score = 100;

            // 连接数评分
            if (stats.ConnectionCount > 100) score -= 20;
            else if (stats.ConnectionCount > 50) score -= 10;

            // 活跃事务评分
            if (stats.ActiveTransactions > 50) score -= 20;
            else if (stats.ActiveTransactions > 20) score -= 10;

            // 缓存命中率评分
            if (stats.CacheHitRate < 60) score -= 20;
            else if (stats.CacheHitRate < 80) score -= 10;

            // 平均查询时间评分
            if (stats.AverageQueryTime > 500) score -= 20;
            else if (stats.AverageQueryTime > 200) score -= 10;

            // 慢查询评分
            if (stats.SlowQueryCount > 10) score -= 20;
            else if (stats.SlowQueryCount > 5) score -= 10;

            return Math.Max(0, score);
        }
    }

    /// <summary>
    /// 数据库性能统计DTO
    /// </summary>
    public class DatabasePerformanceStatsDto
    {
        public DateTime Timestamp { get; set; }
        public int ConnectionCount { get; set; }
        public int ActiveTransactions { get; set; }
        public double CacheHitRate { get; set; }
        public double AverageQueryTime { get; set; }
        public int SlowQueryCount { get; set; }
        public List<IndexUsageStatDto> IndexUsageStats { get; set; }
        public List<TableSizeStatDto> TableSizeStats { get; set; }
    }

    /// <summary>
    /// 索引使用统计DTO
    /// </summary>
    public class IndexUsageStatDto
    {
        public string TableName { get; set; }
        public string IndexName { get; set; }
        public int UsageCount { get; set; }
        public int TotalSeeks { get; set; }
        public int TotalScans { get; set; }
        public int TotalLookups { get; set; }
        public int TotalUpdates { get; set; }
    }

    /// <summary>
    /// 表大小统计DTO
    /// </summary>
    public class TableSizeStatDto
    {
        public string TableName { get; set; }
        public long RowCount { get; set; }
        public long TotalSpaceKB { get; set; }
        public long DataSpaceKB { get; set; }
        public long IndexSpaceKB { get; set; }
    }

    /// <summary>
    /// 数据库优化建议DTO
    /// </summary>
    public class DatabaseOptimizationRecommendationDto
    {
        public string Type { get; set; }
        public string Severity { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public string Recommendation { get; set; }
    }

    /// <summary>
    /// 数据库健康状态DTO
    /// </summary>
    public class DatabaseHealthStatusDto
    {
        public string Status { get; set; }
        public int HealthScore { get; set; }
        public DateTime Timestamp { get; set; }
        public List<HealthCheckItem> Checks { get; set; }
    }

    /// <summary>
    /// 健康检查项
    /// </summary>
    public class HealthCheckItem
    {
        public string Name { get; set; }
        public dynamic Value { get; set; }
        public string Status { get; set; }
        public string Threshold { get; set; }
    }
}